# coding=utf-8
import json

import tornado

from db.model import Static
from db.user import User
from view import getMeta


class confPage(tornado.web.RequestHandler):
    headIcos = {
        '竹笋': ['http://7xqn9l.com1.z0.glb.clouddn.com/ico-zhusun.png', 'selected'],
        '苹果': ['http://7xqn9l.com1.z0.glb.clouddn.com/ico-apple.jpg', ''],
        '安卓': ['http://7xqn9l.com1.z0.glb.clouddn.com/ico-android.jpg', ''],
        '书籍': ['http://7xqn9l.com1.z0.glb.clouddn.com/ico-book0.jpg', ''],
        '道路': ['http://7xqn9l.com1.z0.glb.clouddn.com/ico-way.jpg', ''],
        '自定义': ['head.jpg', ''],
    }

    def get(self):
        meta = getMeta()
        if meta:
            title = meta['title']
            domain = meta['domain']
            headico = meta['headico']
            signature = meta.get('signature', '')
            auth_name = meta.get('auth_name', title)
        else:
            title = ''
            domain = ''
            headico = ''
            signature = ''
            auth_name = '匿名'
        self.render('conf.html', auth_name=auth_name, title=title, signature=signature, domain=domain,
                    headIcos=self.headIcos)


class conf_submit(tornado.web.RequestHandler):
    def post(self):
        password = self.get_argument("password")
        title = self.get_argument('title')
        signature = self.get_argument('signature')
        domain = self.get_argument('domain')
        headico = self.get_argument('headico')
        auth_name = self.get_argument('auth_name')
        if password == User.user_info['password']:
            if title and domain and headico:
                User.db.connect()
                dict = {
                    'title': title,
                    'signature': signature,
                    'domain': domain,
                    'headico': headico,
                    'auth_name': auth_name
                }
                meta = Static.filter(Static.key == 'meta')
                if len(meta) > 0:
                    meta = meta[0]
                    meta.value = json.dumps(dict)
                    meta.save()
                else:
                    meta = Static.create(key='meta', value=json.dumps(dict))
                self.write(json.dumps({
                    'code': 1,
                    'msg': '保存成功'
                }))
            else:
                self.write(json.dumps({
                    'code': 0,
                    'msg': '信息不完整'
                }))
        else:
            self.write(json.dumps({
                'code': -1,
                'msg': '密码错误'
            }))
